class Expense < ActiveRecord::Base
	belongs_to :user
	belongs_to :group
	has_many :individuals, :dependent => :destroy
	
	serialize :party
	
	validates_presence_of :name, :amount, :pay_id, :group_id, :user_id
	validates_numericality_of :amount
	
	def Expense.paytypes
	  {
	    :GROUP_SPLIT => 1,
  	  :MULT_SPLIT => 2,
  	  :OWES_ME => 3
	  }
  end
	
	def Expense.paginate_expenses(group, page)
		Expense.paginate :conditions => {:group_id => group}, :order => 'created_at DESC', :per_page => 10, :page => page
	end
	
	def is_readable_by(user, parent = nil)
		self.user.group_id.eql?(user.group_id)
	end
  
	def owes_for_expense(user)
	  as_payer = Individual.find_where_payer_by_expense(user, self)
  	total = 0
	
  	for i in as_payer
  		total += i.amount
  	end
  	total
  end
  
  def owed_for_expense(user)
  	as_payee = Individual.find_where_payee_by_expense(user, self)
  	total = 0
	
  	for i in as_payee
  		total += i.amount
  	end
  	total
  end
  
  def paid?
    self.individuals.select {|x| x.paid == false}.empty?
  end
  
  def make_individuals
  	group_users = user.group.users.select {|x| x != @user}
  	
  	if(self.pay_id == Expense.paytypes[:GROUP_SPLIT]) #Group Split
  		each_owe = self.amount/(group_users.length + 1)
  		for user in group_users
  		  user = User.find(user);
				indv = Individual.new(:payee => self.user.id, :payer => user.id, :amount => each_owe, :paid => false, :con => false)
				indv.expense = self
				indv.save
  		end
  	elsif(self.pay_id == Expense.paytypes[:MULT_SPLIT]) #Multiple Split
  		each_owe = self.amount/(self.party.length + 1)
  		for user in self.party
  		  user = User.find(user);
  			indv = Individual.new(:payee => self.user.id, :payer => user.id, :amount => each_owe, :paid => false, :con => false)
  			indv.expense = self
				indv.save
  		end
  	elsif(self.pay_id == Expense.paytypes[:OWES_ME]) #Owes
  		for user in self.party
  		  user = User.find(user);
  			indv = Individual.new(:payee => self.user.id, :payer => user.id, :amount => self.amount, :paid => false, :con => false)
  			indv.expense = self
  			indv.save
  		end
  	end
  end
	
	def validate
		if(pay_id != Expense.paytypes[:GROUP_SPLIT]) #If it's not a group sort
			if(party == nil) #Party should not be nil
				errors.add(:party, "Please select involved parties")
			else
				
				puts "Party " + party.to_s
				puts user_id.to_s
				if(pay_id == Expense.paytypes[:MULT_SPLIT]) #If multiple split
					if(party.length < 1) #Must include self
						errors.add(:party, "You must select at least one person to split with")
					end
				end
				
				
				if(pay_id == Expense.paytypes[:OWES_ME]) #If owe-owe
		      if(party.length < 1) #Must include self
						errors.add(:party, "You must select at least one person")
					end
				end
			end
		end
		
		
	end	
	
		
	
end
